package sk.fiit.vppj.eventmanager.graph;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;

/**
 * Class responsible for creating xml form of graph which suites with prescribed form. This xml file is for DashBoard javascript
 * implementation for creating graphs.
 * 
 * @author Marek
 * 
 */
final class XmlGraphExporter {
	private List<Coordinate> data = null;
	private String graphName;
	private final static Logger log = Logger.getLogger( XmlGraphExporter.class.getName() );

	
	public XmlGraphExporter(List<Coordinate> data, String graphName) {
		this.data = data;
		this.graphName = graphName;
	}

	/**
	 * Generates xml in correct form, using graph data
	 * @param myWriter insta
	 */
	private void generateXML(XMLStreamWriter myWriter) {
		try {
			myWriter.writeStartDocument( "UTF-8", "1.0" );

			myWriter.writeStartElement( "graph" );
			myWriter.writeAttribute( "animation", "1" );
			myWriter.writeAttribute( "caption", this.graphName );
			myWriter.writeAttribute( "showNames", "1" );
			myWriter.writeAttribute( "rotateNames", "1" );
			myWriter.writeAttribute( "decimalPrecision", "0" );

			for ( Coordinate coord : this.data ) {
				myWriter.writeStartElement( "set" );
				myWriter.writeAttribute( "name", coord.getX() );
				myWriter.writeAttribute( "hoverText", coord.getX() );
				myWriter.writeAttribute( "value", String.valueOf( coord.getY() ) );
				myWriter.writeEndElement();
			}
			myWriter.writeEndElement();
			myWriter.writeEndDocument();

		}
		catch ( XMLStreamException e ) {
			log.log( Level.WARNING, "XML for creating graphs failed!", e );
			e.printStackTrace();
		}
	}

	/**
	 * Saves generated xml into file
	 * @param file
	 */
	public void save(File file) {

		try {
			XMLOutputFactory myFactory = XMLOutputFactory.newInstance();
			XMLStreamWriter myWriter = myFactory.createXMLStreamWriter( new FileOutputStream( file ), "UTF-8" );
			generateXML( myWriter );
			myWriter.flush();
			myWriter.close();

		}
		catch ( FileNotFoundException e ) {
			log.log( Level.WARNING, "File not found!" );
			e.printStackTrace();
		}
		catch ( XMLStreamException e ) {
			log.log( Level.WARNING, "Can't create Xml for creating graphs!" );
			e.printStackTrace();
		}
	}
}
